/*
 * Created by Julia on 2016/4/28.
 */

define(['jquery', 'domReady!', 'appLocalStorage', 'appConst', 'model/global', 'model/role', 'appMessageBox', 'stringUtils'], function ($, domReady, appLocalStorage, appConst, global, roleM, msgBox, stringUtils) {
    var components = {};
    var data = {
        searchFields: {},
        search_key: ""
    };
    var that;
    return {
        init: function () {
            that = this;
            data.search_key = appConst.searchKey.search_role_key + global.getUserId();

            components = {
                txt_search_roleName: $('#txt_search_roleName'),
                tbl_roles: $('#tbl_roles'),
                btn_simple_search: $('#btn_simple_search')
            };

            that.initSearchBar();
            that.initRoleTable();
        },
        initRoleTable: function () {
            //that.setSearchCondition();
            components.tbl_roles.dataTable({
                "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'><'col-sm-6 col-xs-12 hidden-xs'>>r" +
                "t" +
                "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "processing":true,
                "pageLength": global.getPageSize(),
                "paging": true,
                //"pagingType":   "full_numbers",
                "autoWidth": false,
                "serverSide": true,
                "language": appConst.table_language(),
                "ordering": false,
                "ajax": {
                    "url": 'role/list',
                    "type": "POST",
                    "dataSrc": "body",
                    "traditional": true,
                    "data": function (params) {
                        return that.getSearchCondition(params);
                    },
                    "error": function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                    }
                },
                "columns": [
                    {"data":null},
                    {"data":"id"},
                    {"data":"name"},
                    {"data":"description"},
                    {"data":"enabled"},
                    {"data":null}
                ],
                "columnDefs": [
                    {
                        "targets": [1],
                        "visible": false
                    },
                    {
                        "targets": [4],
                        "render": function (data, type, full) {
                            var enabled = '';
                            if (full.enabled == 'ENABLE') {
                                enabled = '<span class="label label-success">' + $.i18n.prop('ROLE_STATUS_ACTIVE') + '</span>';
                            } else if (full.enabled == 'DISABLE') {
                                enabled = '<span class="label label-warning">' + $.i18n.prop('ROLE_STATUS_LOCK') + '</span>';
                            }
                            return enabled;
                        }
                    },
                    {
                        "targets": [5],
                        "render": function (data, type, full) {
                            var id = full.id;
                            var name = full.name;
                            var aHref = "";
                            if (name != "Administrator") {
                                aHref = '<a href="javascript:void(0);" class="deleteRoleConfirm_role" data-id="' + id + '" data-name="' + name + '">' + $.i18n.prop("GLOBAL_DELETE") + '</a> '
                            }
                            else {
                                aHref = "";
                            }
                            var operate = '<div class="center">'
                                    /* + '<a href="javascript:void(0);" class="details-control">Resource</a>' + ' '*/
                                + '<a href="#role/edit/' + id + '" class="details-control">' + $.i18n.prop("GLOBAL_EDIT") + '</a>' + ' '
                                + aHref
                                + '</div>';
                            return operate;
                        }
                    }
                ]
            });

            /*Deal with the index number of column 1;*/
            global.drawNumber_bg(components.tbl_roles, function () {
                components.tbl_roles.find(".deleteRoleConfirm_role").unbind('click').on('click', function (obj) {
                    that.deleteRoleConfirm({id: $(this).attr("data-id"), name: $(this).attr("data-name")});
                });
            });
        },
        initSearchBar: function () {
            components.btn_simple_search.click(function (e) {
                data.searchFields.search_LIKE_name = components.txt_search_roleName.val();
                appLocalStorage.setLocal(data.search_key, JSON.stringify(data.searchFields));
                that.loadRoleTable();
            });
        },
        loadRoleTable: function () {
            components.tbl_roles.dataTable().api().ajax.url('role/list').load();
        },
        deleteRoleConfirm: function (role) {
            var id  = role.id;
            var name = role.name;
            msgBox.show({
                title: $.i18n.prop('MESSAGEBOX_CONFIRM_TITLE'),
                content: "" + $.i18n.prop("ROLE_DELETE_SUBMIT", [name]) +" <p class='text-align-right'>" +
                "<button type='submit' data-roleid='"+ id + "' class='btn btn-primary btn-sm deleteRole_role"+ id +"'>" + $.i18n.prop("GLOBAL_BUTTON_YES") + "</button> " +
                "<a href='javascript:void(0);' class='btn btn-danger btn-sm'>" + $.i18n.prop("GLOBAL_BUTTON_NO") + "</a></p>",
                type: 'normal',
                timeout: false,
                clean: true
            });

            $('#divSmallBoxes').find(".deleteRole_role" + id).unbind('click').on('click', function (e) {
                e.preventDefault();
                that.deleteRole(role);
            });

        },
        deleteRole: function (role) {
            roleM.deleteRole(role.id, function (d) {
                msgBox.successBox({
                    content: $.i18n.prop('GLOBAL_DELETE_SUCCESS', role.name)
                });

                that.loadRoleTable();
            }, function (msg) {
                //console.log(msg);
            })
        },
        getSearchCondition: function (params) {
            data.searchFields = {
                search_LIKE_name :components.txt_search_roleName.val()
            };

            var queryCondition;
            var localParam = appLocalStorage.getLocal(data.search_key);
            if (stringUtils.isNotBlank(localParam)) {
                queryCondition = JSON.parse(localParam);

                if (stringUtils.isNotBlank(queryCondition.search_LIKE_name)) {
                    components.txt_search_roleName.val(queryCondition.search_LIKE_name);
                }
                data.searchFields = queryCondition;
            }

            $.extend(params, data.searchFields);
            params['draw'] = params.draw;

            return params;
        }
    };
});
